package me.nuncio.ggplay.codec;

import com.google.inject.Inject;
import me.nuncio.ggplay.pdu.Pdu;

import java.nio.ByteBuffer;

public class DefaultTranscoder implements Transcoder {

    @Inject DefaultTranscoder(){}

    @Override
    public void encode(Pdu pdu, ByteBuffer buf) {
        buf.flip();
        buf.putInt(pdu.getLength());
        buf.put(pdu.getContent().getBytes());
    }

    @Override
    public Pdu decode(ByteBuffer buf) {
        buf.flip();
        int length = buf.getInt();
        byte[] contentBytes = new byte[length];
        buf.get(contentBytes);
        return new Pdu(length, new String(contentBytes));
    }
}
